package com.zb.zeus.common.redis.service;

import com.zb.zeus.common.redis.utils.RedisSequenceUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * 获取code
 *
 * @author zhichong
 */
@Component
public class CodeService {


    private static String DIVISION = ":";

    @Value("${spring.application.name:'undefine'}")
    private String system;

    /**
     * 获取编码
     *
     * @param redisTemplate redis
     * @param key           编码前缀
     * @param formatLength  格式长度
     * @return
     */
    public String getCode(String key, Integer formatLength, RedisTemplate redisTemplate) {
        return key + RedisSequenceUtil.generate(key, formatLength, redisTemplate);
    }

    /**
     * 获取编码
     *
     * @param key          编码前缀
     * @param formatLength 格式长度
     * @return
     */
    public String getCode(String key, Integer formatLength) {
        return key + RedisSequenceUtil.generate(system + DIVISION + key, formatLength);
    }

    /**
     * 获取编码
     * redis 中的流水本日有效
     *
     * @param redisTemplate redis
     * @param key           编码前缀
     * @param formatLength  格式长度
     * @return
     */
    public String getCodeDate(String key, Integer formatLength, RedisTemplate redisTemplate) {
        String timestr = DateFormatUtils.format(new Date(), "yyyyMMdd");
        Date date = getTomorrow(new Date());
        return key + timestr + RedisSequenceUtil.generate(key, date, formatLength, redisTemplate);
    }

    /**
     * 获取编码
     * redis 中的流水本日有效
     *
     * @param key          编码前缀
     * @param formatLength 格式长度
     * @return
     */
    public String getCodeDate(String key, Integer formatLength) {
        String timestr = DateFormatUtils.format(new Date(), "yyyyMMdd");
        Date date = getTomorrow(new Date());
        return key + timestr + RedisSequenceUtil.generate(system + DIVISION + key, date, formatLength);
    }


    /**
     * 获取第二天 凌晨时间
     *
     * @param date
     * @return
     */
    public static Date getTomorrow(Date date) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        ca.add(Calendar.DAY_OF_YEAR, 1);
        //失效的时间
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);
        Date tomorrow = ca.getTime();
        return tomorrow;
    }

    /**
     * 获取下一位自建组织的编码
     * @return 自建组织的编码
     */
    public Long getOrgBusinessCode(String key, Long defaultValue){
        key = system + DIVISION + key;
        return RedisSequenceUtil.nextVal(key, defaultValue, null);
    }

}
